package com.chucang.shucang.ttp.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chucang.shucang.ttp.paycenter.bo.CFCAInfoBO;
import com.huifu.saturn.cfca.CFCASignature;
import com.huifu.saturn.cfca.SignResult;
import com.huifu.saturn.cfca.VerifyResult;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/10/13 17:54
 * @description 加签解签工具
 */
@Slf4j
@UtilityClass
public class HFSignUtil {
    /**
     * 加签工具
     *
     * @param jsonStr
     * @param cfcaInfoBo
     * @return
     */
    public String sign(String jsonStr, CFCAInfoBO cfcaInfoBo) {
        SignResult signResult = CFCASignature.signature(cfcaInfoBo.getPfxFile(), cfcaInfoBo.getPfxFilePwd(), jsonStr, "utf-8");

        if ("000".equals(signResult.getCode())) {
            log.info("加签结果：{}", signResult.getSign());
            return signResult.getSign();
        } else {
            return "fail";
        }
    }

    /**
     * 解签工具
     *
     * @param responseJson
     * @param cfcaInfoBo
     * @return
     */
    public String parseCVResult(String responseJson, CFCAInfoBO cfcaInfoBo) {
        log.info("加解签参数：{}", cfcaInfoBo.toString());
        log.info("待解签内容：{}", responseJson);
        // 将json格式字符串转换为json对象
        JSONObject jsonObject = JSONUtil.parseObj(responseJson);
        // 取得返回数据密文
        String sign = jsonObject.getStr("check_value");
        // 进行验签，参数1为汇付商户号，固定为100001
        VerifyResult verifyResult = CFCASignature.verifyMerSign(cfcaInfoBo.getNpayMerId(), sign, "utf-8", cfcaInfoBo.getCerFile());
        if ("000".equals(verifyResult.getCode())) {
            // 取得内容
            String content = new String(verifyResult.getContent(), StandardCharsets.UTF_8);
            log.info("解签结果：{}", content);
            return content;
        } else {
            log.info("解签失败");
            return "fail";
        }
    }

    /**
     * 验签
     *
     * @param sign
     * @param cfcaInfoBo
     * @return
     */
    public String parseResult(String sign, CFCAInfoBO cfcaInfoBo) {
        // 进行验签，参数1为汇付商户号，固定为100001
        VerifyResult verifyResult = CFCASignature.verifyMerSign(cfcaInfoBo.getNpayMerId(), sign,
                "utf-8", cfcaInfoBo.getCerFile());

        log.info("校验结果：{}", verifyResult.toString());
        if ("000".equals(verifyResult.getCode())) {
            // 内容
            String content = new String(verifyResult.getContent(),
                    StandardCharsets.UTF_8);
            log.info("content = {}", content);
            return content;
        } else {
            return "fail";
        }
    }
}
